package org.mall.modules.shop.controller;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.mall.common.api.vo.Result;
import org.mall.common.api.vo.UserInfo;
import org.mall.common.aspect.annotation.AutoLog;
import org.mall.common.exception.ServiceException;
import org.mall.common.constant.AppMessageTypeEnum;
import org.mall.common.system.query.QueryGenerator;
import org.mall.common.system.util.JwtUtil;
import org.mall.common.util.*;
import org.mall.common.util.json.JacksonUtils;
import org.mall.convert.ShopConvert;
import org.mall.modules.message.service.AppMessageService;
import org.mall.modules.pojo.common.AppMessageDTO;
import org.mall.modules.pojo.shop.*;
import org.mall.modules.seller.entity.Seller;
import org.mall.modules.seller.service.ISellerService;
import org.mall.modules.shop.entity.Shop;
import org.mall.modules.shop.entity.ShopClerkRelationShip;
import org.mall.modules.shop.entity.ShopSellerRe;
import org.mall.modules.shop.service.IShopClerkRelationShipService;
import org.mall.modules.shop.service.IShopService;
import org.mall.modules.shoptype.entity.ShopTypeNameDTO;
import org.mall.modules.shoptype.entity.ShopTypeRe;
import org.mall.modules.shoptype.service.IShopTypeReService;
import org.mall.modules.shoptype.service.IShopTypeService;
import org.mall.modules.system.client.SmsClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 商铺
 * @Author: jeecg-boot
 * @Date: 2019-10-23
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "商铺")
@RestController
@RequestMapping("/shop")
public class ShopController {
    @Autowired
    private IShopService shopService;
    @Autowired
    private  IShopService iShopService;
    @Autowired
    private IShopTypeReService shopTypeReService;

    @Autowired
    private IShopTypeService shopTypeService;
    @Autowired
    private IShopClerkRelationShipService shopClerkRelationShipService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ISellerService sellerService;

    @Autowired
    private AppMessageService appMessageService;
    @Autowired
    private SmsClient smsClient;

    /**
     * 分页列表查询
     *
     * @param shop
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "商铺-分页列表查询")
    @ApiOperation(value = "商铺-分页列表查询", notes = "商铺-分页列表查询")
    @GetMapping(value = "/app/shopList")
    public Result<IPage<Shop>> queryPageList(Shop shop,
                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                             HttpServletRequest req) {
        Result<IPage<Shop>> result = new Result<IPage<Shop>>();
        shop.setCoordinate(null);
        QueryWrapper<Shop> queryWrapper = QueryGenerator.initQueryWrapper(shop, req.getParameterMap());
        Page<Shop> page = new Page<Shop>(pageNo, pageSize);
        //增加判断条件，只查询未删除的
        queryWrapper.eq("is_delete",0);
        queryWrapper.eq("shop_status",1);

        queryWrapper.select(Shop.class, info -> !info.getColumn().equals("update_time")
                && !info.getColumn().equals("create_time"));
        IPage<Shop> pageList = shopService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    @AutoLog(value = "商铺-分页列表查询")
    @ApiOperation(value = "商铺-根据坐标获取附近", notes = "商铺-分页列表查询")
    @GetMapping(value = "/app/shopListOfRange")
    public Result<?> shopListOfRange(@RequestParam String coordinate , @RequestParam(name = "level",defaultValue = "1",required = false) Integer level,
                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                     HttpServletRequest req) {

        String co;
        try {
             co=GeoHash.encode(coordinate);
            if (co==null){
                return Result.error("坐标信息错误");
            }
        }catch (ServiceException e){
            log.info("用户没有上传位置信息，或提交的位置信息错误，默认返回返回燃气公司为中心的商店列表");
            co="wwdubnq5";
            level=4;
        }

        final String geoCoordinate=co.substring(0,8-5);
        Page page=new Page(pageNo,pageSize);
        IPage<Shop> shopIPage=shopService.getListByCoordinate(page,geoCoordinate);
        List<Shop> shops=shopIPage.getRecords().stream().
                sorted(Comparator.comparingDouble(o-> DistanceUtil.distance(geoCoordinate,o.getCoordinate())))
                .collect(Collectors.toList());
        IPage<ShopDTO> shopDTOIPage=new Page().setTotal(shopIPage.getTotal()).setSize(pageSize).setCurrent(pageNo);
        List<ShopDTO> shopDTOS=ShopConvert.INSTANCE.convert2(shops);
        List<ShopTypeNameDTO> shopTypeNameDTOS=shopTypeService.getGoodSTypeNameList(shopDTOS.stream().map(ShopDTO::getId).collect(Collectors.toList()));
        Map<String,List<ShopTypeNameDTO>> map=shopTypeNameDTOS.stream().collect(Collectors.groupingBy(ShopTypeNameDTO::getShopId));

        Iterator<String> iterator=map.keySet().iterator();
        while (iterator.hasNext()){
            String shopId=iterator.next();
            for (ShopDTO shopDTO:shopDTOS){
                if (shopId.equals(shopDTO.getId())){
                    shopDTO.setTypeNameList(map.get(shopId).stream().map(ShopTypeNameDTO::getTypeName).collect(Collectors.toList()));
                }
            }
        }
        shopDTOIPage.setRecords(shopDTOS);
        return Result.ok(shopDTOIPage);
    }
    /**
     * 分页列表查询--web
     *
     * @param shopTpyeVO
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "商铺-分页列表查询")
    @ApiOperation(value = "商铺-分页列表查询", notes = "商铺-分页列表查询")
    @GetMapping(value = "/web/shopList")
    public Result<IPage<ShopVO>> queryWebPageList(ShopTpyeVO shopTpyeVO,
                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                HttpServletRequest req) {
        Result<IPage<ShopVO>> result = new Result<IPage<ShopVO>>();
        Shop shop=new Shop();
        BeanUtils.copyProperties(shopTpyeVO,shop);
        QueryWrapper<Shop> queryWrapper = QueryGenerator.initQueryWrapper(shop, req.getParameterMap());
        Page<Shop> page = new Page<Shop>(pageNo, pageSize);
        //增加判断条件，只查询未删除的
        queryWrapper.eq("is_delete",0);
        queryWrapper.select(Shop.class, info -> !info.getColumn().equals("update_time")
                && !info.getColumn().equals("create_time"));
        IPage<Shop> pageList = shopService.page(page, queryWrapper);
        IPage<ShopVO> shopVOIPage=new Page<>();
        shopVOIPage.setTotal(pageList.getTotal()).setSize(pageList.getSize()).setRecords(ShopConvert.INSTANCE.convert8(pageList.getRecords()));
        List<ShopTypeRe> list=shopTypeReService.getGoodsTypeListByShopIds(shopVOIPage.getRecords().stream().map(ShopVO::getId).collect(Collectors.toList()));
        Map<String,List<ShopTypeRe>> map=list.stream().collect(Collectors.groupingBy(ShopTypeRe::getShopId));
        Iterator<String> iterator=map.keySet().iterator();
        while(iterator.hasNext()){
            String shopId=iterator.next();
            for (ShopVO shopVO:shopVOIPage.getRecords()){
                if (shopVO.getId().equals(shopId)){
                    shopVO.setGoodsTyeList(map.get(shopId).stream().map(ShopTypeRe::getTypeId).collect(Collectors.toList()));
                    break;
                }
            }
        }
        result.setSuccess(true);
        result.setResult(shopVOIPage);
        return result;
    }


    @GetMapping("/merchant/list")
    public Result<?>  getAllShopListOfSeller( @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize){


        UserInfo userInfo = JwtUtil.getUserInfoByToken();
        log.info("");
        if (0==userInfo.getType()){
            return Result.ok(shopService.getAllShopListOfSeller(new Page().setTotal(pageNo).setSize(pageSize), JwtUtil.getUserIdByToken()));

        }else {
            return Result.ok(shopService.getShopPageListOfClerk(new Page().setTotal(pageNo).setSize(pageSize), JwtUtil.getUserIdByToken()));

        }


    }

    /**
     * 管理员添加商铺
     * shopTypeReService.removeByShopId(reviewVO.getId());
     *             List<ShopTypeRe> list=reviewVO.getGoodsTypeList().stream().map(o->{ ShopTypeRe temp=new ShopTypeRe();
     *             temp.setTypeId(o);temp.setShopId(reviewVO.getId());
     *             return temp;
     *             }).collect(Collectors.toList());
     *             if (!list.isEmpty()){
     *                 shopTypeReService.saveBatch(list);
     *             }
     * @return
     */
    @AutoLog(value = "商铺-添加")
    @ApiOperation(value = "商铺-添加", notes = "商铺-添加")
    @PostMapping(value = "/web/add")
    public Result<?> add(@Valid @RequestBody ShopAddDTO shopAddDTO,BindingResult bindingResult) {
        if (bindingResult.hasErrors()){
            return Result.error(JacksonUtils.toJSONString(bindingResult));
        }
        Result<Shop> result = new Result<Shop>();
        Shop shop=ShopConvert.INSTANCE.convert5(shopAddDTO);
        try {
            String shopId= UUIDGenerator.generate();
            Seller seller=sellerService.getById(shopAddDTO.getSellerId());
            if (seller==null){
                return Result.error("该商户不存在");
            }
            shop.setId(shopId);
            shop.setMobile(seller.getMobile());
            shop.setCoordinate(GeoHash.encode(shop.getCoordinate()));
            shop.setStatus(0);
            shop.setIsDelete(0);
            shopService.save(shop);
            //往商户商铺关联表中添加记录
            shopService.saveRelationshipTable(shopId,shopAddDTO.getSellerId());
            //先删除商铺与可添加商品类型
            shopTypeReService.removeByShopId(shopId);
            List<ShopTypeRe> list=shopAddDTO.getGoodsTyeList().stream().map(o->{ ShopTypeRe temp=new ShopTypeRe();
                temp.setTypeId(o);temp.setShopId(shopId);
                return temp;
            }).collect(Collectors.toList());
            if (!list.isEmpty()){
            //新增商铺与可添加商品类型
                shopTypeReService.saveBatch(list);
            }
            AppMessageDTO appMessageDTO=new AppMessageDTO();
            appMessageDTO.setContent("商铺添加："+shop.getShopName()+"于"+DateUtils.formatDate(new Date())+"添加成功");
            appMessageDTO.setTitle("商铺添加");
            appMessageDTO.setCreator("管理员");
            appMessageDTO.setType(AppMessageTypeEnum.MERCHANT_STORE_MESSAGE_NOTICE.getValue());
            appMessageDTO.setReceiver(shopAddDTO.getSellerId());
            appMessageDTO.setTemplateId(1);
            appMessageDTO.setCreateTime(DateUtils.getDate());
            appMessageDTO.setEntitiesId(shop.getId());
            appMessageService.sendAppMessageToUser(appMessageDTO);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败:"+e.getMessage());
        }
        return result;
    }

    /**
     * 商户添加商铺
     *
     * @return
     */
    @AutoLog(value = "商铺-添加")
    @ApiOperation(value = "商铺-添加", notes = "商铺-添加")
    @PostMapping(value = "/merchant/add")
    public Result<?> merchantAdd(@Valid @RequestBody ShopAddDTO shopAddDTO,BindingResult bindingResult) {
        if (bindingResult.hasErrors()){
            return Result.error(JacksonUtils.toJSONString(bindingResult.getAllErrors()));
        }
        Result<Shop> result = new Result<Shop>();
        Shop shop=ShopConvert.INSTANCE.convert5(shopAddDTO);
        String sellerId = JwtUtil.getUserInfoByToken().getUserId();
            QueryWrapper<Shop> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("shop_name",shop.getShopName());
            Shop dbData=shopService.getOne(queryWrapper);
            Seller seller=sellerService.getById(sellerId);
            if (seller==null){
                return Result.error("商户信息异常");
            }
            if (dbData!=null) {
                return result.error500("商铺名称已存在");
            }
            shop.setId(UUIDGenerator.generate());
            shop.setMobile(seller.getMobile());
            //获取商铺id
            shop.setCreateTime(new Date());
            try {
                String[] coordinat=shop.getCoordinate().split(",");
                shop.setCoordinate(GeoHash.encode(Double.parseDouble(coordinat[0]),Double.parseDouble(coordinat[1])));

            }catch (Exception e){
                return Result.error("商店坐标有误");
            }
        try {
            shopService.save(shop);
            //往商户商铺关联表中添加记录
            shopService.saveRelationshipTable(shop.getId(),sellerId);
            AppMessageDTO appMessageDTO=new AppMessageDTO();
            appMessageDTO.setContent("商铺添加："+shop.getShopName()+"于"+DateUtils.formatDate(new Date())+"添加成功");
            appMessageDTO.setTitle("商铺添加");
            appMessageDTO.setCreator("");
            appMessageDTO.setType(AppMessageTypeEnum.MERCHANT_STORE_MESSAGE_NOTICE.getValue());
            appMessageDTO.setReceiver(JwtUtil.getUserIdByToken());
            appMessageDTO.setTemplateId(1);
            appMessageDTO.setCreateTime(DateUtils.getDate());
            appMessageDTO.setEntitiesId(shop.getId());
            appMessageService.sendAppMessageToUser(appMessageDTO);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    @PostMapping("/merchant/updateShopStatus")
    public Result<?> updateShopStatus(@RequestBody StatusVo vo){
        shopService.updateStatus(vo.getShopId(),vo.getStatus());
        return Result.ok();

    }
    /**
     * 编辑--web
     *
     * @return
     */
    @AutoLog(value = "商铺-编辑")
    @ApiOperation(value = "商铺-编辑", notes = "商铺-编辑")
    @PostMapping(value = "/web/edit")
    public Result<?> edit(@RequestBody ShopUpdateDTO shopUpdateDTO,BindingResult bindingResult) {
        if (bindingResult.hasErrors()){
            return Result.error(JacksonUtils.toJSONString(bindingResult));
        }
        Result<Shop> result = new Result<Shop>();
        Shop shop=ShopConvert.INSTANCE.convert6(shopUpdateDTO);
        String co=shop.getCoordinate();
        if (co!=null&&co.contains(",")){
            try {
                co=GeoHash.encode(co);
                shop.setCoordinate(co);
            }catch (Exception e){

            }

        }
        Shop shopEntity = shopService.getById(shop.getId());
        if (shopEntity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = shopService.updateById(shop);
            //先删除商铺与可添加商品类型
            shopTypeReService.removeByShopId(shopUpdateDTO.getId());
            List<ShopTypeRe> list=shopUpdateDTO.getGoodsTyeList().stream().map(o->{ ShopTypeRe temp=new ShopTypeRe();
                temp.setTypeId(o);temp.setShopId(shopUpdateDTO.getId());
                return temp;
            }).collect(Collectors.toList());
            if (!list.isEmpty()){
                //新增商铺与可添加商品类型
                shopTypeReService.saveBatch(list);
            }
            //TODO 返回false说明什么？
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    @GetMapping("/web/detail")
    public Result<?> webDetail(@RequestParam String shopId) {
        Result<Shop> result = new Result<Shop>();
        Shop shopEntity = shopService.getDetailById(shopId);
        if (shopEntity == null) {
            result.error500("未找到对应实体");
        }
        return Result.ok(shopEntity);
    }
    /**
     * 通过id删除 逻辑删除商铺
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "商铺-通过id删除", notes = "商铺-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            shopService.removeShopById(id);
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "商铺-批量删除")
    @ApiOperation(value = "商铺-批量删除", notes = "商铺-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<Shop> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<Shop> result = new Result<Shop>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.shopService.removeShopByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "商铺-通过id查询")
    @ApiOperation(value = "商铺-通过id查询", notes = "商铺-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<Shop> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<Shop> result = new Result<Shop>();
        Shop shop = shopService.getById(id);
        if (shop == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(shop);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
        // Step.1 组装查询条件
        QueryWrapper<Shop> queryWrapper = null;
        try {
            String paramsStr = request.getParameter("paramsStr");
            if (oConvertUtils.isNotEmpty(paramsStr)) {
                String deString = URLDecoder.decode(paramsStr, "UTF-8");
                Shop shop = JSON.parseObject(deString, Shop.class);
                queryWrapper = QueryGenerator.initQueryWrapper(shop, request.getParameterMap());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<Shop> pageList = shopService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "商铺列表");
        mv.addObject(NormalExcelConstants.CLASS, Shop.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("商铺列表数据", "导出人:Jeecg", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<Shop> listShops = ExcelImportUtil.importExcel(file.getInputStream(), Shop.class, params);
                shopService.saveBatch(listShops);
                return Result.ok("文件导入成功！数据行数:" + listShops.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }



    /**
     * 店铺分配店员
     * @param shopClerkRelationShip
     * @return
     */
    @PostMapping("/merchant/storeDistributionClerk")
    public Result StoreDistributionClerk(@Valid @RequestBody ShopClerkRelationShip shopClerkRelationShip, BindingResult bindingResult){
        ShopClerkRelationShip shopClerk;
        if(bindingResult.hasErrors()){
            return Result.error(JacksonUtils.toJSONString(bindingResult.getAllErrors()));
        }
        String[] ids = shopClerkRelationShip.getClerkId().split(",");
        for (int i = 0; i<ids.length;i++){
            shopClerk = new ShopClerkRelationShip();
            shopClerk.setShopId(shopClerkRelationShip.getShopId());
            shopClerk.setClerkId(ids[i]);
            shopClerkRelationShipService.save(shopClerk);
        }
        return Result.ok("分配成功");
    }


    /**
     * 查看店铺详情
     * @param shopId
     * @return
     */
    @GetMapping("/merchant/shopDetail")
    public Result<?> shopDetail(@RequestParam(name = "shopId", required = true) String shopId){

        Result<Shop> result = new Result<Shop>();

        Shop shopEntity = shopService.getById(shopId);

        return Result.ok(shopEntity);
    }

    @GetMapping("/app/shopDetail")
    public Result<?> ShopDetailForApp(@RequestParam(name = "shopId", required = true) String shopId){

        Result<Shop> result = new Result<Shop>();

        Shop shopEntity = shopService.getById(shopId);
        ShopDetailForAppVO shopVO=new ShopDetailForAppVO();
        BeanUtils.copyProperties(shopEntity,shopVO);
        return Result.ok(shopVO);
    }
    @PostMapping("/merchant/updateShopInfo")
    public Result<?> updateShopInfo(@Valid @RequestBody ShopUpdateDTO shopUpdateDTO,BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return Result.error(JacksonUtils.toJSONString(bindingResult.getAllErrors()));
        }
        Shop shop=ShopConvert.INSTANCE.convert6(shopUpdateDTO);
        String co=shop.getCoordinate();
        if (co!=null&&co.contains(",")){
            try {
                co=GeoHash.encode(co);
                shop.setCoordinate(co);
            }catch (Exception e){
            }
        }
        ShopSellerRe shopSellerRe=shopService.getShopSellerShipByShopId(shop.getId());
        if (!ObjectUtils.StringsIsEquals(JwtUtil.getUserIdByToken(), shopSellerRe.getSellerId())){
            return Result.error("不是该商户的店铺");
        }
        try {
            //TODO  是否需要修改为待审核
            shop.setMobile(null);
            shop.setUpdateTime(new DateTime());
            shopService.updateById(shop);
            return  Result.ok("更新成功");
        }catch (Exception e){
            return Result.error("更新失败");
        }


    }

    /**
     * @param params
     * @return
     */
    @PostMapping("/merchant/delete")
    public Result<?> sellerDeleteShopById(@RequestBody Map<String ,Object> params){
        if (params.get("shopId")==null){
            return Result.error("缺少商铺id");
        }
        String shopId= (String) params.get("shopId");
        String code=(String) params.get("code");
        ShopSellerRe shopSellerRe=shopService.getShopSellerShipByShopId(shopId);
        if (!shopSellerRe.getSellerId().equals(JwtUtil.getUserIdByToken())){
            return Result.error("该商铺不属于该商户");
        }
        Shop temp=new Shop();
        temp.setId(shopId);
        temp.setIsDelete(1);
        try {
            Shop shop=shopService.getById(shopId);
            if (shop!=null){
            }
        String c=(String)redisUtil.getSellerCode(shop.getMobile());
            if (code==null||!code.equals(c)){
                return Result.error("验证码错误");
            }

            shopService.updateById(temp);
            shopService.deleteSellerShopRelationByShopId(shopId);
        }catch (Exception e){
            log.error(e.getMessage());
            return Result.error("删除失败");
        }
        Shop detail = shopService.getDetailById(shopId);
        AppMessageDTO appMessageDTO = new AppMessageDTO();
        appMessageDTO.setContent("商铺删除："+detail.getShopName()+"于"+DateUtils.formatDate(new Date())+"删除成功");
        appMessageDTO.setTitle("商铺删除");
        appMessageDTO.setCreator("");
        appMessageDTO.setType(AppMessageTypeEnum.MERCHANT_STORE_MESSAGE_NOTICE.getValue());
        appMessageDTO.setReceiver(JwtUtil.getUserIdByToken());
        appMessageDTO.setTemplateId(1);
        appMessageDTO.setCreateTime(DateUtils.getDate());
        appMessageDTO.setEntitiesId(shopId);
        appMessageService.sendAppMessageToUser(appMessageDTO);
        return Result.ok("删除成功");

    }
    @DeleteMapping("/web/delete")
    public Result<?> webDeleteShopById(@RequestParam(name="id",required=true) String id){
        if (id==null){
            return Result.error("缺少商铺id");
        }
        Shop temp=new Shop();
        temp.setId(id);
        temp.setIsDelete(1);
        try {
            shopService.updateById(temp);
            shopService.deleteSellerShopRelationByShopId(id);
        }catch (Exception e){
            log.error(e.getMessage());
            return Result.error("删除失败");
        }
        Shop detail = shopService.getDetailById(id);
        ShopSellerRe shopSellerId = iShopService.getShopSellerShipByShopId(id);
        AppMessageDTO appMessageDTO = new AppMessageDTO();
        appMessageDTO.setContent("商铺删除："+detail.getShopName()+"于"+DateUtils.formatDate(new Date())+"删除成功");
        appMessageDTO.setTitle("商铺删除");
        appMessageDTO.setCreator("");
        appMessageDTO.setType(AppMessageTypeEnum.MERCHANT_STORE_MESSAGE_NOTICE.getValue());
        appMessageDTO.setReceiver(shopSellerId.getSellerId());
        appMessageDTO.setTemplateId(1);
        appMessageDTO.setCreateTime(DateUtils.getDate());
        appMessageDTO.setEntitiesId(id);
        appMessageService.sendAppMessageToUser(appMessageDTO);
        return Result.ok("删除成功");

    }

    /**
     * 批量删除店铺--web
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/web/deleteWebBatch")
    public Result<Shop> deleteWebBatch(@RequestParam(name="ids",required=true) String ids) {
        Result<Shop> result = new Result<Shop>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.shopService.removeShopByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    @PostMapping("/web/reviewShopInfo")
    public Result reviewShopInfo(@RequestBody ShopReviewVO reviewVO){
        if (reviewVO.getId()==null||reviewVO.getShopStatus()==null||reviewVO.getGoodsTypeList()==null){
            return Result.error("参数不足");
        }
        else {
            shopTypeReService.removeByShopId(reviewVO.getId());
            List<ShopTypeRe> list=reviewVO.getGoodsTypeList().stream().map(o->{ ShopTypeRe temp=new ShopTypeRe();
            temp.setTypeId(o);temp.setShopId(reviewVO.getId());
            return temp;
            }).collect(Collectors.toList());
            if (!list.isEmpty()){
                shopTypeReService.saveBatch(list);
            }
            //更新店铺状态为审核通过 （状态:0：待审核: 1：已审核: 2：审核未通过, ）
            shopService.updateShopStatus(reviewVO.getId(),reviewVO.getShopStatus());
            Shop detail = shopService.getDetailById(reviewVO.getId());
            ShopSellerRe shopSellerId = iShopService.getShopSellerShipByShopId(reviewVO.getId());
            AppMessageDTO appMessageDTO = new AppMessageDTO();
            appMessageDTO.setContent("商铺审核："+detail.getShopName()+"于"+DateUtils.formatDate(new Date())+"审核通过");
            appMessageDTO.setTitle("商铺审核");
            appMessageDTO.setCreator("管理员");
            appMessageDTO.setType(AppMessageTypeEnum.MERCHANT_STORE_MESSAGE_NOTICE.getValue());
            appMessageDTO.setReceiver(shopSellerId.getSellerId());
            appMessageDTO.setTemplateId(1);
            appMessageDTO.setCreateTime(DateUtils.getDate());
            appMessageDTO.setEntitiesId(reviewVO.getId());
            appMessageService.sendAppMessageToUser(appMessageDTO);
            Map<String,String> map = new HashMap<>();
            map.put("content", DateUtils.formatDate(new Date()) + detail.getShopName() +"审核通过");
            smsClient.singleSendMsg(detail.getMobile(),map);
            if (1==reviewVO.getShopStatus()) {
                Shop shop = new Shop();
                shop.setId(reviewVO.getId());
                shop.setWorkType(reviewVO.getWorkType());
                shop.setDivideNum(reviewVO.getDivideNum());
                shop.setDivideType(reviewVO.getDivideType());
                shopService.updateById(shop);
            }
        }
        return Result.ok("操作成功");
    }
    @GetMapping("/web/getShopNameList")
    public Result<?> getShopNameList( String shopName){

        return Result.ok(shopService.getShopNameList(shopName));

    }


}
